var splitPopupResInfo = null;
var subReservationDetailPage = null;
var objsplitRes = null;

function loadRoomOnPopupWithException(roomtypeId,date,span,except,callback,args)
{
	var url = "/popupService";
	var data = { doClass : "loadRoomG",
		roomtype: roomtypeId,
		date: date,
		span: span,
		except: except
	}
	simpleserviceWithArgs(url,data,callback,args);
}

function splitReservationToday(el)
{
	var resId = $(el).attr("res");
	document.splitRes = $(el);
	$("#SplitRoom").dialog({
		width : 525,
		resizable : false,
		modal : true,
		zIndex: 200001,
		show : {
			effect : "blind",
			duration : 500
		},
		open: function(event, ui) {
			var dom = document.splitRes;
			delete document.splitRes;
			$(this).css('overflow', 'hidden');
			$("#SplitRoom").dialog('option','title',addSplitReservation);
			$("#SplitRoom [name='splitToRoom']").find("option").not(":first").remove();
			$("#SplitRoom [name='splitToRoomType']").find("option").not(":first").remove();
			var obj = getObjFromCell(dom[0]);
			var df = new Date(obj.rlD);
			var dt = df.addDate(obj.rlS);
			loadAllRoomInReservation(resId,fillSplitPopupToday,df,dt);
	    },
		close : function() {
			splitPopupResInfo = null;
			objsplitRes = null;
		}
	});
}

function splitReservationExtend(el)
{
	var resId = $(el).attr("res");
	document.splitRes = $(el);
	$("#SplitRoom").dialog({
		width : 525,
		resizable : false,
		modal : true,
		zIndex: 200001,
		show : {
			effect : "blind",
			duration : 500
		},
		open: function(event, ui) {
			var dom = document.splitRes;
			delete document.splitRes;
			$(this).css('overflow', 'hidden');
			$("#SplitRoom").dialog('option','title',extendReservation);
			$("#SplitRoom [name='splitToRoom']").find("option").not(":first").remove();
			$("#SplitRoom [name='splitToRoomType']").find("option").not(":first").remove();
			var obj = getObjFromCell(dom[0]);
			var df = new Date(obj.rlD).addDate(obj.rlS);
			var dt = df.addDate(1);
			loadAllRoomInReservation(resId,fillSplitPopupExtend,df,dt);
	    },
		close : function() {
			splitPopupResInfo = null;
			objsplitRes = null;
		}
	});
}

function splitReservationTodayDetailPage(resId,subResv)
{
	$("#SplitRoom").dialog({
		width : 525,
		resizable : false,
		modal : true,
		zIndex: 200001,
		show : {
			effect : "blind",
			duration : 500
		},
		open: function(event, ui) {
			$(this).css('overflow', 'hidden');
			subReservationDetailPage = subResv;
			$("#SplitRoom").dialog('option','title',addSplitReservation);
			$("#SplitRoom [name='splitToRoom']").find("option").not(":first").remove();
			$("#SplitRoom [name='splitToRoomType']").find("option").not(":first").remove();
			var df = new Date(getCurrentTabData().ResData.date);
			var dt = new Date(getCurrentTabData().ResData.dateTo);
			loadAllRoomInReservation(resId,fillSplitPopupToday,df,dt);
	    },
		close : function() {
			splitPopupResInfo = null;
			subReservationDetailPage = null;
			objsplitRes = null;
		}
	});
}

function splitReservationExtendDetailPage(resId,subResv,from,to)
{
	objsplitRes = {};
	objsplitRes.extentSplitFrom = from;
	objsplitRes.extentSplitTo = to;
	$("#SplitRoom").dialog({
		width : 525,
		resizable : false,
		modal : true,
		zIndex: 200001,
		show : {
			effect : "blind",
			duration : 500
		},
		open: function(event, ui) {
			$(this).css('overflow', 'hidden');
			subReservationDetailPage = subResv;
			$("#SplitRoom").dialog('option','title',extendReservation);
			$("#SplitRoom [name='splitToRoom']").find("option").not(":first").remove();
			$("#SplitRoom [name='splitToRoomType']").find("option").not(":first").remove();
			loadAllRoomInReservation(resId,fillSplitPopupExtend,objsplitRes.extentSplitFrom,objsplitRes.extentSplitTo);
	    },
		close : function() {
			splitPopupResInfo = null;
			subReservationDetailPage = null;
			objsplitRes = null;
		}
	});
}

function ApplyCalendarSplitPopup()
{
	var from = new Date(splitPopupResInfo.date);
	var minD = getDate();
	
	if(minD < from)
		minD = from;
	
	var maxD = minD.addDate(splitPopupResInfo.span);
	
	$("#SplitRoom [name='srTxtFrom']").datepicker({
        changeMonth: true,
        changeYear: true,
        showOn: 'button',
        monthNamesShort: ShortMonth,
		monthNames: ShortMonth,
		dayNamesShort: ShortDay,
		dayNames: ShortDay,
        buttonImage: '/images/components/editres/carendar.png',
        buttonImageOnly: true,
        dateFormat: SharedData.General.dateFormat.dateTimeFormat,
        onSelect: function(dateText) {
        	var newDate = dateText.getDate();  
        	$("#SplitRoom [name='srTxtTo']").datepicker('option', {minDate: newDate.addDate(1)});
        	splitPopupChangeRoomType();
        }
    });
	
	$("#SplitRoom [name='srTxtTo']").datepicker({
        changeMonth: true,
        changeYear: true,
        showOn: 'button',
        monthNamesShort: ShortMonth,
		monthNames: ShortMonth,
		dayNamesShort: ShortDay,
		dayNames: ShortDay,
        buttonImage: '/images/components/editres/carendar.png',
        buttonImageOnly: true,
        dateFormat: SharedData.General.dateFormat.dateTimeFormat,
        onSelect: function(dateText) {
        	splitPopupChangeRoomType();
        }
    });
	

	$("#SplitRoom [name='srTxtFrom']").datepicker( "option" , {
	    minDate: minD,
	    maxDate: maxD.addDate(-1)} );
	$("#SplitRoom [name='srTxtTo']").datepicker( "option" , {
	    minDate: minD.addDate(1),
	    maxDate: maxD} );
	if(objsplitRes!=null){
		$("#SplitRoom [name='srTxtFrom']").datepicker().datepicker('setDate', objsplitRes.extentSplitFrom);
		$("#SplitRoom [name='srTxtTo']").datepicker().datepicker('setDate', objsplitRes.extentSplitTo);
	}else{
		$("#SplitRoom [name='srTxtFrom']").datepicker().datepicker('setDate', minD);
		$("#SplitRoom [name='srTxtTo']").datepicker().datepicker('setDate', maxD);
	}
}

function ApplyCalendarSplitPopupExtend()
{
	var to = new Date(splitPopupResInfo.dateTo);
	
	$("#SplitRoom [name='srTxtFrom']").datepicker({
        changeMonth: true,
        changeYear: true,
        showOn: 'button',
        monthNamesShort: ShortMonth,
		monthNames: ShortMonth,
		dayNamesShort: ShortDay,
		dayNames: ShortDay,
        buttonImage: '/images/components/editres/carendar.png',
        buttonImageOnly: true,
        dateFormat: SharedData.General.dateFormat.dateTimeFormat
    });
	
	$("#SplitRoom [name='srTxtTo']").datepicker({
        changeMonth: true,
        changeYear: true,
        showOn: 'button',
        monthNamesShort: ShortMonth,
		monthNames: ShortMonth,
		dayNamesShort: ShortDay,
		dayNames: ShortDay,
        buttonImage: '/images/components/editres/carendar.png',
        buttonImageOnly: true,
        dateFormat: SharedData.General.dateFormat.dateTimeFormat,
        onSelect: function(dateText) {
        	splitPopupChangeRoomType();
        }
    });
	$("#SplitRoom [name='srTxtFrom']").datepicker( "option" , {
	    minDate: to,
	    maxDate: to});
	$("#SplitRoom [name='srTxtTo']").datepicker( "option" , {
	    minDate: to.addDate(1),
	    maxDate: null});
	if(objsplitRes!=null){
		$("#SplitRoom [name='srTxtFrom']").datepicker().datepicker('setDate', objsplitRes.extentSplitFrom);
		$("#SplitRoom [name='srTxtTo']").datepicker().datepicker('setDate', objsplitRes.extentSplitTo);
	}
}

function splitPopupChangeRoomType()
{
	$("#SplitRoom [name='splitToRoom']").find("option").not(":first").remove();
	
	var roomtype = $("#SplitRoom [name='splitToRoomType']").val();
	var from = $("#SplitRoom [name='srTxtFrom']").datepicker("getDate");
	var to = $("#SplitRoom [name='srTxtTo']").datepicker("getDate");
	var span = daysBetween(from,to);

	if(subReservationDetailPage != null)
		except = res;
	else
		except = splitPopupResInfo.id;
	loadRoomOnPopupWithException(roomtype,from.toFormatString('yyyy-MM-dd'),span,except,fillSplitPopupRoom,null);
}

function fillSplitPopupRoom(data)
{
	var objArray = JSON.parse(data);
	for(i=0;i<objArray.length;i++)
		$("#SplitRoom [name='splitToRoom']").append("<option value='" + objArray[i].id + "'>" + objArray[i].roomName + "</option>");
}

function fillSplitPopup(data)
{
	var objArray = JSON.parse(data);
	splitPopupResInfo = objArray.ResDate;
	fillSplitPopupTable(objArray.Object);
	fillSplitPopupExistRoom(objArray);
}
function fillSplitPopupExistRoom(objArray){
	$("#SplitRoom [name='splitToRoomType']").find("option").not(":first").remove();
	for(i=0;i<SharedData.RoomType.length;i++){
		var selected = (SharedData.RoomType[i].id == objArray.roomtype)? " selected='true'" : "";
		$("#SplitRoom [name='splitToRoomType']").append("<option value='" + SharedData.RoomType[i].id + "'"+selected+">" + SharedData.RoomType[i].shortName + "</option>");
	}

	$("#SplitRoom [name='splitToRoom']").find("option").not(":first").remove();
	var ids = objArray.ExRoom.split(",");
	for(var i=0;i<ids.length;i++)
	{
		var room = getObjectFromSharedData(SharedData.Room,ids[i]);
		var selected = (room.id == objArray.next)? " selected='true'" : "";
		$("#SplitRoom [name='splitToRoom']").append("<option value='" + room.id + "'"+selected+">" + room.roomName + "</option>");
	}
}
function fillSplitPopupTable(objArray){
	var roomTypeString = objArray[0].roomTypeShortName + " ";
	for(var i=0;i<objArray.length;i++)
	{
		roomTypeString += (i==0)? "(" : ",";
		roomTypeString += objArray[i].roomName;
	}
	roomTypeString += ")";
	$("span[name='roomtypename'][popup='split']").text(roomTypeString);

	if(objArray.length > 1)
	{
		$("#SplitRoom").find("hr").css("display","");
		$("#SplitRoomDetail").css("display","");
		
		var html = "<table style='width:100%'><tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>";
		html = html.format(simpleLabel_roomType,simpleLabel_Date,simpleLabel_room);
		for(var i=0;i<objArray.length;i++)
		{
			var dateFrom = new Date(objArray[i].dateFrom).getFormatedString();
			var dateTo = new Date(objArray[i].dateTo).getFormatedString();
			html += "<tr><td>" + objArray[i].roomTypeShortName + "</td><td>" + dateFrom + " - " + dateTo + "</td><td>" + objArray[i].roomName + "</td></tr>";
		}
		html += "</table>";
		$("#SplitRoomDetail").html(html);
		$("#SplitRoom").dialog('option','height','auto');
		$("#SplitRoom").parents(".ui-dialog").css("height","auto")
	}
	else
	{
		$("#SplitRoom").find("hr").css("display","none");
		$("#SplitRoomDetail").css("display","none");
		$("#SplitRoom").dialog('option','height','auto');
		$("#SplitRoom").parents(".ui-dialog").css("height","auto")
	}
	
	$("#SplitRoom").focus();
	
	ApplyCalendarSplitPopup();
}

function fillSplitPopupToday(data)
{
	fillSplitPopup(data);
	ApplyCalendarSplitPopup();
}

function fillSplitPopupExtend(data)
{
	fillSplitPopup(data);
	ApplyCalendarSplitPopupExtend();
}

function splitReservation()
{
	var room = $("#SplitRoom [name='splitToRoom']");
	
	if(room.val() == 0)
	{
		simpleDialog("Please Choose Room");
	}
	else
	{
		var from = $("#SplitRoom [name='srTxtFrom']").datepicker("getDate").toFormatString('yyyy-MM-dd');
		var to = $("#SplitRoom [name='srTxtTo']").datepicker("getDate").toFormatString('yyyy-MM-dd');
		var roomType = $("#SplitRoom [name='splitToRoomType']").val();
		var room = $("#SplitRoom [name='splitToRoom']").val();
		waitingDialog({});
		callSplitReservation(splitPopupResInfo.id,from,to,roomType,room,splitReservationCallback);
	}
}

function splitReservationCallback(data)
{
	var objArray = JSON.parse(data);
	if(!objArray.Result)
		simpleDialog("Split Fail");
	else
		closeWaitingDialog();
		var Tabs = getTabsData(splitPopupResInfo.id);

		if(Tabs != null){
			if(objArray.SubReservationList!=null)ResetSplitTable(objArray.SubReservationList,Tabs);
			if(objArray.ChargeList!=null)ResetChargeList(objArray.ChargeList,Tabs);
			if(objArray.PackageByDate!=null)ResetPackageTable(objArray.PackageByDate,Tabs);
			if(objArray.ReservationDate!=null){
				Tabs.ResData.date = objArray.ReservationDate.date;
				Tabs.ResData.span = objArray.ReservationDate.span;
			}
			DisplayDetail();
		}
		cerltimespan(savedSpan);
		$('#SplitRoom').dialog('close');
}

function callSplitReservation(resId,from,to,roomtype,room,callback)
{
	var url = "/subReservationService";
	var data = { func : "SplitReservation",
			resId: resId,
			from: from,
			to: to,
			roomtype: roomtype,
			room: room
	}
	if(isOpenResTab(res)) data.min = 1;
	simpleservice(url,data,callback);
}

function loadAllRoomInReservation(resId,callback,df,dt)
{
	simpleservice("/subReservationService",{func:"GetAllRoomInReservation",resId: resId,df:df.toSystemFormat(),dt:dt.toSystemFormat()},callback);
}

function load_and_render_split_reservation(data)
{
	var Tabs = getTabsData(JSON.parse(data)[0].id);
	load_split_table_success(data,Tabs);
	renderReservationTableDetailPage(Tabs);
}

function load_split_table_success(data,Tabs)
{
	if(Tabs == null) return;
	var objArray = JSON.parse(data);
	
	Tabs.SplitTable = objArray;
	
	Tabs.ResData.date = objArray.ResDate.date;
	Tabs.ResData.span = objArray.ResDate.span;
	
	fillReservationDetail(Tabs);
}

function renderReservationTableDetailPage(Tabs)
{
	if(Tabs == null || Tabs.SplitTable == null)
		return;
	objArray = Tabs.SplitTable;
	var table = $('table[name=subReservationList]').find('tbody');
	table.find('tr').not(":first").remove();
	for(var i=0;i<objArray.Object.length;i++)
	{
		var from =  new Date(objArray.Object[i].dateFrom);
		var to = new Date(objArray.Object[i].dateTo);
		var resId = objArray.Object[i].resId;
		var span = daysBetween(from,to);
		
		var shortName = objArray.Object[i].roomTypeShortName;
		var dateString = from.getFormatedString() + ' - ' + to.getFormatedString();
		var roomName = objArray.Object[i].roomName;
		
		if(objArray.Object.length == 1)
		{
			shortName = "&nbsp;";
			dateString = "&nbsp;";
			roomName = "&nbsp;";
			span = "&nbsp;";
		}
		str = '<tr style="height:24px;" resId="{0}" from="{9}" to="{10}">'
			+ '<td style="margin-left:10px;" name="roomtype">'
			+ '<div roomtypeId="{7}" {5}>'
			+ '{1}'
			+ '</div>'
			+ '</td>'
			+ '<td style="text-align:center;">'
			+ '{2}'
			+ '</td>'
			+ '<td name="room">'
			+ '<div style="text-align:right" roomId="{8}" {6}>'
			+ '{3}'
			+ '</div>'
			+ '</td>'
			+ '<td colspan="6" style="text-align:center;">'
			+ '{4}'
			+ '</td>'
			+ '</tr>';
		
		var editable = "class=\"link\" onclick=\"EditSplitReservationRoom($(this).parents('tr:first'));\"";
		if(new Date(objArray.Object[i].dateFrom) < getDate())
			editable = "";
		str = str.format(resId,shortName,dateString,roomName,span,editable,editable,objArray.Object[i].roomTypeId,objArray.Object[i].roomId,from,to);
		table.append($(str));
	}
}